<template>
  <div class="app-container">
    讲师列表
    <!--查询表单-->
  <el-card class="operate-container" shadow="never">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="searchObj.name" placeholder="讲师名" />
      </el-form-item>

      <el-form-item label="头衔">
        <el-select v-model="searchObj.professional" clearable placeholder="头衔">
          <el-option value="高级讲师" label="高级讲师"/>
          <el-option value="首席讲师" label="首席讲师"/>
        </el-select>
      </el-form-item>

      <el-form-item label="入驻时间">
        <el-date-picker
          v-model="searchObj.joinDateBegin"
          placeholder="开始时间"
          value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="-">
        <el-date-picker
          v-model="searchObj.joinDateEnd"
          placeholder="结束时间"
          value-format="yyyy-MM-dd" />
      </el-form-item>

        <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
        <el-button type="default" @click="resetData()">清空</el-button>
    </el-form>
  </el-card>

<!-- 工具按钮 -->
<el-card class="operate-container" shadow="never">
  <i class="el-icon-tickets" style="margin-top: 5px"></i>
  <span style="margin-top: 5px">数据列表</span>
  <el-button class="btn-add" @click="add()" style="margin-left: 10px;">添加</el-button>
  <el-button class="btn-add" @click="batchRemove()" >批量删除</el-button>
</el-card>

    <!-- 表格 -->
    <el-table
      :data="list"
      border
      stripe
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column
        label="#"
        width="50">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="relName" label="名称" width="100" />
      <el-table-column label="头像" width="120" prop="avatar">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" style="width: 100px; height: 77px;">
        </template>
      </el-table-column>
      <el-table-column label="头衔" width="100" prop="professional">
        <!-- <template slot-scope="scope">
          <el-tag v-if="scope.row.professional === '1'" type="success" size="mini">高级讲师</el-tag>
          <el-tag v-if="scope.row.professional === '0'" size="mini">首席讲师</el-tag>
        </template> -->
      </el-table-column>
      <el-table-column prop="degree" label="学历" width="120" />
      <el-table-column prop="description" label="简介" width="200" />
      <el-table-column prop="qq" label="QQ" width="120" />
      <el-table-column prop="createTime" label="入驻时间" value-format="yyyy-MM-dd" width="196" />
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="removeById(scope.row.id)">删除</el-button>
          <el-button type="text" size="mini" @click="handleEdit(scope.row.id)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
      <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />

    <el-dialog :title=addtitle :visible.sync="dialogFormVisible" :show-close=close >
      <!-- 输入表单 -->
      <el-form label-width="120px">
        <el-form-item label="讲师名称">
          <el-input v-model="teacher.relName" />
        </el-form-item>
        <el-form-item label="入驻时间">
          <el-date-picker v-model="teacher.joinDate" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="讲师学历">
          <el-select v-model="teacher.degree" placeholder="请选择学历">
            <!--
              数据类型一定要和取出的json中的一致，否则没法回填
              因此，这里value使用动态绑定的值，保证其数据类型是number
              -->
            <el-option value='专科及以下' label="专科及以下"/>
            <el-option value='专科' label="专科"/>
            <el-option value='本科' label="本科"/>
            <el-option value='本科及以上' label="本科及以上"/>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择头衔">
          <el-select v-model="teacher.professional">
            <!--
              数据类型一定要和取出的json中的一致，否则没法回填
              因此，这里value使用动态绑定的值，保证其数据类型是number
              -->
            <el-option value="高级讲师" label="高级讲师"/>
            <el-option value="首席讲师" label="首席讲师"/>
          </el-select>
        </el-form-item>
        <el-form-item label="QQ">
          <el-input v-model="teacher.qq"/>
        </el-form-item>
        <el-form-item label="讲师资历">
          <el-input v-model="teacher.description" :rows="10" type="textarea"/>
        </el-form-item>

        <!-- 讲师头像 -->
        <!-- 讲师头像 -->
        <el-form-item label="讲师头像">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :action="BASE_API+'/upload'"
            class="avatar-uploader">
            <img v-if="teacher.avatar" :src="teacher.avatar" style="width: 600px; height: 460px;">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveOrUpdate">保存</el-button>
          <el-button @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
//引入定义接口js文件
import teacherApi from '@/api/teacher'

export default {
  data() {  //初始值
    return {
      list: [], // 讲师列表
      total: 0, // 总记录数
      page: 1, // 当前页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询条件
      multipleSelection: [],// 批量删除选中的记录列表
      dialogFormVisible:false,
      close:false,
      addtitle: "",
      teacher:{},
      BASE_API: 'http://localhost:8080/teacher',
    }
  },
  created() { //页面渲染之前
    this.fetchData()
  },
  methods:{ //具体方法
    //批量删除
    batchRemove() {
      //判断非空
      if(this.multipleSelection.length===0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将删除该讲师信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idList = []
          // [1,2,3]
          //遍历数组
          for(var i=0;i<this.multipleSelection.length;i++) {
            var obj = this.multipleSelection[i]
            var id = obj.id
            //放到数组
            idList.push(id)
          }
          //调用接口删除
          teacherApi.batchRemove(idList)
            .then(response => {
                //提示
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新
                this.fetchData()
            })
        })
    },

    handleEdit(id){
      this.openDialog(id)
      this.addtitle='修改通知'
    },

    openDialog(id){
      if (id!=null){
        teacherApi.getTeacherById(id).then(response => {
          this.teacher = response.data;
        })
      }
      this.dialogFormVisible=true
    },
    //添加和修改
    saveOrUpdate() {
      if(!this.teacher.id) { //没有id，添加
        this.save()
      } else { //有id，修改
        this.update()
      }
    },

    //添加
    save() {
      //添加
      teacherApi.saveTeacher(this.teacher)
        .then(response => {
          //提示
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          //跳转列表页面
          this.dialogFormVisible = false
          this.teacher={}
          this.fetchData()
        })
    },
    //修改
    update() {
      //添加
      teacherApi.updateTeacher(this.teacher)
        .then(response => {
          //提示
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          //跳转列表页面
          this.dialogFormVisible = false
          this.teacher={}
          this.fetchData()
        })
    },


    back(){
      this.dialogFormVisible=false
      this.teacher= {}
    },

    //复选框发生变化，调用方法，选中复选框行内容传递
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      // console.log(res)
      if (res.code==200) {
        // console.log(res)
        this.teacher.avatar = res.data
        console.log(this.teacher)
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },

    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败（http失败）')
    },

    // 上传校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    //跳转到添加表单页面
    add() {
      this.dialogFormVisible = true
    },

    fetchData() {
      //ajax
      teacherApi.pageList(this.page,this.limit,this.searchObj)
        .then(response => {
          this.list = response.data.records
          console.log(this.list);
          this.total = response.data.total
        })

    },
    //改变每页显示记录数
    changePageSize(size) {
      this.limit = size
      this.fetchData()
    },
    //改变页码数
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },
    //清空
    resetData() {
      this.searchObj = {}
      this.fetchData()
    },
    //讲师删除
    removeById(id) {
      this.$confirm('此操作将删除该讲师信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //调用接口删除
          teacherApi.removeTeacherId(id)
            .then(response => {
                //提示
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新
                this.fetchData()
            })
        })
    }
  }
}
</script>
